package com.xiannimei.util;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiannimei.util.httpUtils.HttpRequest;
import com.xiannimei.util.httpUtils.HttpResponse;
import com.xiannimei.util.httpUtils.HttpUtil;

public class SFUtil {

    private static final Logger log = LoggerFactory.getLogger(SFUtil.class);

    /**
     * <h1>queryDeliveryFee 获取SF运费，返回运费。null表示查询失败</h1><br/>
     * String fromProvince from省<br/>
     * String fromCity from市<br/>
     * String destProvince dest省<br/>
     * String destCity dest市<br/>
     * String weights 重量<br/>
     * String volumnWeight 体积重（长*宽*高），单位cm
     * */
    public static BigDecimal queryDeliveryFee(String fromProvince, String fromCity, String destProvince, String destCity, String weights, String volumnWeight) {
        HttpUtil httpUtil = new HttpUtil();

        HttpRequest req = new HttpRequest();
        req.setUrl("http://www.sf-express.com/ows-dfp/$%7Bpath%7D/rate_enquiry!getProdPriceList.action");
        req.setParams("lang=sc&region=cn&oriProvince=" + fromProvince + "&oriCity=" + fromCity + "&destProvince=" + destProvince + "&destCity=" + destCity + "&weights=" + weights + "&volumnWeight=" + volumnWeight + "&cargoType=");
        List<Header> headers = new ArrayList<Header>();
        Header h1 = new Header();
        h1.setName("Referer");
        h1.setValue("http://www.sf-express.com/ows-dfp/rate_enquiry.html?lang=SC&region=CN");
        headers.add(h1);
        Header h2 = new Header();
        h2.setName("x-requested-with");
        h2.setValue("XMLHttpRequest");
        headers.add(h2);

        BigDecimal res = null;
        try {
            HttpResponse resp = httpUtil.request(req, null, 200, true);
            String body = resp.getBody();
            log.info(body);
            JSONArray cargos = JSONArray.fromObject(body);
            for (int i = 0; i < cargos.size(); i++) {
                JSONObject cargo = cargos.getJSONObject(i);
                if ("T6".equals(cargo.getString("cargoTypeCode"))) {
                    res = new BigDecimal(cargo.getString("freight"));
                }
            }
        } catch (HttpException e) {
            log.warn("", e);
        } catch (IOException e) {
            log.warn("", e);
        }

        return res;
    }

    public static void main(String[] args) {
        System.out.println(SFUtil.queryDeliveryFee("98624", "021", "98602", "010", "20", "6"));
    }

}
